package com.rxh.service;

import com.rxh.activeMQ.ConsumerMessageListener;
import com.rxh.cache.CoreAcquirerAccountCache;
import com.rxh.cache.MerchantPayCache;
import com.rxh.exception.PayException;
import com.rxh.pojo.Result;
import com.rxh.pojo.core.CoreAcquirerAccount;
import com.rxh.pojo.core.CoreMerchantOrder;
import com.rxh.pojo.core.CoreOrder;
import com.rxh.pojo.core.CoreOrderDetail;
import com.rxh.pojo.cross.BankResult;
import com.rxh.pojo.merchant.MerchantPay;
import com.rxh.service.core.CoreMerchantOrderService;
import com.rxh.service.core.CoreOrderDetailService;
import com.rxh.service.core.CoreOrderService;
import com.rxh.utils.SystemConstant;
import org.apache.activemq.ScheduledMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.ObjectMessage;

/**
 * Created with IntelliJ IDEA.
 * User: 陈俊雄
 * Date: 2018/10/18
 * Time: 10:03
 * Project: Management
 * Package: com.rxh.service
 */
@Service
public class PaymentNotifyService {

    private final static Logger logger = LoggerFactory.getLogger(PaymentNotifyService.class);

    @Resource
    private CoreOrderService coreOrderService;
    @Resource
    private CoreOrderDetailService coreOrderDetailService;
    @Resource
    private CoreMerchantOrderService coreMerchantOrderService;

    private final MerchantNotifyService merchantNotifyService;
    private final RecordService recordService;
    private final MerchantPayCache merchantPayCache;
    private final CoreAcquirerAccountCache coreAcquirerAccountCache;
    private final JmsTemplate queueJmsTemplate;

    @Autowired
    public PaymentNotifyService(MerchantPayCache merchantPayCache, RecordService recordService, MerchantNotifyService merchantNotifyService, CoreAcquirerAccountCache coreAcquirerAccountCache, JmsTemplate queueJmsTemplate) {
        this.merchantPayCache = merchantPayCache;
        this.recordService = recordService;
        this.merchantNotifyService = merchantNotifyService;
        this.coreAcquirerAccountCache = coreAcquirerAccountCache;
        this.queueJmsTemplate = queueJmsTemplate;
    }

    public Result updateOrderAndDoNotify(BankResult bankResult) throws PayException {
        CoreOrder order = coreOrderService.selectByPrimaryKey(bankResult.getOrderId()).getData();
        if (order == null) {
            return new Result(Result.FAIL, "平台订单：" + bankResult.getOrderId() + "，不存在！");
        }
        CoreMerchantOrder merchantOrder = coreMerchantOrderService.selectByOrderId(order.getId()).getData();
        MerchantPay merchantPay = merchantPayCache.getBySiteIdOrMerchantId(order.getSiteId(), order.getMerId(), order.getCurrency());
        CoreOrderDetail orderDetail = coreOrderDetailService.selectByOrderId(order.getId()).getData();
        CoreAcquirerAccount acquirerAccount = coreAcquirerAccountCache.getById(order.getAccountId());
        if (order.getBankStatus() == SystemConstant.BANK_STATUS_PENDING_PAYMENT) {
            queueJmsTemplate.send(ConsumerMessageListener.ORDER_NOTIFY, session -> {
                ObjectMessage objectMessage = session.createObjectMessage(bankResult);
                // 5秒后发送异步通知，减少异步通知比同步通知快的情况。
                objectMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, 5 * SystemConstant.SECOND_TO_MILLISECOND);
                return objectMessage;
            });
            String msg = "订单：" + order.getId() + "，同步交易未完成，已将异步通知消息存入消息队列！";
            logger.warn(msg);
            return new Result(Result.SUCCESS, msg);
        }
        switch (bankResult.getStatus()) {
            case SystemConstant.BANK_STATUS_SUCCESS:
                order.setFinanceStatus(SystemConstant.FINANCE_STATUS_LIQUIDATION);
                order.setBankParam(bankResult.getParam());
                break;
            case SystemConstant.BANK_STATUS_FAIL:
                break;
            case SystemConstant.BANK_STATUS_UNPAID:
                break;
            case SystemConstant.BANK_STATUS_PENDING_PAYMENT:
                break;
            case SystemConstant.BANK_STATUS_RESEND:
                break;
            case SystemConstant.BANK_STATUS_TIME_OUT:
                break;
            default:
                break;
        }
        order.setBankInfo(bankResult.getBankResult());
        order.setBankTime(bankResult.getBankTime());
        order.setBankParam(bankResult.getParam());
        recordService.updateOrder(order);
        merchantNotifyService.sendMerchantNotify(order, orderDetail, merchantPay, merchantOrder, acquirerAccount, bankResult);
        return new Result(Result.SUCCESS, "订单更新完成！");
    }
}